package com.atguigu.gulimall.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * @program: gulimall
 * @author: yangshen
 * @description:
 * @create: 2020-06-09 20:49
 **/
public class ValidListValueConstraintValidator implements ConstraintValidator<ValidListValue, Integer> {

    private Set<Integer> set = new HashSet<>();

    /**
     * 初始化方法：会将将标记 @ValidListValue 的详细信息返回
     * @param constraintAnnotation 校验注解的类型
     */
    @Override
    public void initialize(ValidListValue constraintAnnotation) {
        int[] values = constraintAnnotation.value();
        for(int value: values){
            set.add(value);
        }
    }

    /**
     * 判断是否校验成功
     * @param value 传入@ValidListValue注解的值  即待校验的值
     * @param context 上下文
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return set.contains(value);
    }
}
